﻿using System;
using System.Collections.Generic;
using System.Text;
using SecureConnection.Utils;


namespace RemoteCode
{
    internal class InitializedLocalClass
    {
        public InitializedLocalClass(object classObject_, string name_)
        {
            this.classObject = classObject_;
            this.name = name_;
            this.type = classObject.GetType();
        }

        public static Result Dispose(ref ByteArrayReader br, Nexum host)
        {
            string name = "";
            try
            {
                name = br.ReadString();
            }
            catch (Exception ex) { return new Result(true, ex, NexumError.PacketParsingError, null); }

            lock (host.InitializedClasses)
            {
                if (!host.InitializedClasses.ContainsKey(name))
                    return new Result(true, null, NexumError.ClassNotFound, null);

                host.InitializedClasses[name].classObject = null;
                host.InitializedClasses[name].name = "";

                host.InitializedClasses.Remove(name);
            }

            return new Result(false, null, NexumError.Success, null);
        }            
        public static Result Invoke(ref ByteArrayReader br, Nexum host)
        {          
            string name = "";
            string methodName = null;
            object[] parameters = null;
            bool pointer = false;

            try
            {
                pointer = br.ReadByte() == 1;
                name = br.ReadString();
            
                methodName = br.ReadString();
                parameters = SerializationHelper.DeserializeArray(ref br);
            }
            catch (Exception ex) { return new Result(true, ex, NexumError.PacketParsingError, null); }

            InitializedLocalClass l = null;
            lock (host.InitializedClasses)
            {
                if (!host.InitializedClasses.ContainsKey(name))
                    return new Result(true, null, NexumError.ClassNotFound, null);

                l = host.InitializedClasses[name];
            }

            return InvokeHelper.InvokeMethod(l.type, methodName, parameters, l.classObject, pointer, host);
        }

        public object classObject;
        public string name;
        public Type type;
    }
}
